package com.manage.oauth.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.manage.common.core.enums.GrantType;
import com.manage.oauth.constants.ResponseEnum;
import com.manage.oauth.dto.OAuth2UserDto;
import com.manage.system.api.dto.SysRoleDto;
import com.manage.system.api.dto.SysUserDto;
import com.manage.system.api.entity.SysRole;
import com.manage.system.api.feign.RemoteSystemUser;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangqing
 * @version V1.0
 * @description 用户管理业务类
 * @date 4/3/2021 2:48 PM
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserDetailsService {
    private final RemoteSystemUser systemUser;
    private final HttpServletRequest request;
    private final PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        SysUserDto sysUserDto = systemUser.loadByUsername(loginName);
        String clientId = request.getParameter("client_id");
        String password = request.getParameter("password");
        String grantType = request.getParameter("grant_type");

        ResponseEnum.USER_NOT_FOUND.assertIsEmpty(sysUserDto);

        if (GrantType.PASSWORD.getCode().equals(grantType)) {
            sysUserDto.setClientId(clientId);
            sysUserDto.setGrantType(grantType);
            if (!loginName.equals(sysUserDto.getLoginName()) || !passwordEncoder.matches(password, sysUserDto.getPassword())) {
                throw new UsernameNotFoundException(ResponseEnum.USERNAME_PASSWORD_ERROR.getMessage());
            }
        }
        List<SysRoleDto> role = sysUserDto.getRoles();
        List<String> ageList = role.stream().map(SysRole::getRoleCode).collect(Collectors.toList());
        JSONObject jsonObject = JSONUtil.parseObj(sysUserDto);
        jsonObject.putOpt("roles",ageList);
        OAuth2UserDto oAuth2UserDto = new OAuth2UserDto(jsonObject);
        ResponseEnum.ACCOUNT_DISABLED.assertIsFalse(oAuth2UserDto.isEnabled());
        ResponseEnum.ACCOUNT_DEL.assertIsTrue(oAuth2UserDto.getDelFlag());
        return oAuth2UserDto;
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
        ;
    }
}
